//
//  DM_TemplateConfig.swift
//  Dream_OrmFramework
//
//  Created by Dream on 15/12/27.
//  Copyright © 2015年 Tz. All rights reserved.
//

import UIKit

//解析XML
class DM_TemplateConfig: NSObject,XMLParserDelegate {
    
    let LABEL_ORM:String = "orm"
    let LABEL_KEY:String = "key"
    let LABEL_ITEM:String = "item"
    let ATTRIBUTE_BEAN_NAME:String = "className"
    let ATTRIBUTE_DAO_NAME:String = "daoName"
    let ATTRIBUTE_TABLE_NAME:String = "tableName"
    let ATTRIBUTE_COLUMN:String = "column"
    let ATTRIBUTE_IDENTITY:String = "identity"
    let ATTRIBUTE_PROPERTY:String = "property"
    let ATTRIBUTE_COLUMN_TYPE:String = "columnType"
    let ATTRIBUTE_TYPE:String = "propertyType"
    
    var parser:XMLParser!
    var orm:DM_Orm!
    var ormDic = [String: DM_Orm]()
    var key:DM_OrmKey!
    var item:DM_OrmItem!
    
    static let sharedInstace = DM_TemplateConfig()
    
    
    func initXml(){
        self.parser = XMLParser(contentsOf: NSURL(fileURLWithPath: Bundle.main.path(forResource: "DM_User.orm", ofType: "xml")!) as URL)
        self.parser.delegate = self
        // 开始解析
        self.parser.parse()
    }
    
    // 监听解析节点的属性
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]){
        switch elementName{
        case LABEL_ORM:
            self.orm = DM_Orm()
            self.orm.className = attributeDict[ATTRIBUTE_BEAN_NAME]!
            self.orm.tableName = attributeDict[ATTRIBUTE_TABLE_NAME]!
            self.orm.daoName = attributeDict[ATTRIBUTE_DAO_NAME]!
            self.ormDic["构建者模式_ORM_SWIFT."+self.orm.className] = orm
            break
        case LABEL_KEY:
            self.key = DM_OrmKey()
            self.key.column = attributeDict[ATTRIBUTE_COLUMN]!
            self.key.columnType = attributeDict[ATTRIBUTE_COLUMN_TYPE]!
            self.key.property = attributeDict[ATTRIBUTE_PROPERTY]!
            self.key.propertyType = attributeDict[ATTRIBUTE_TYPE]!
            if(attributeDict[ATTRIBUTE_IDENTITY] == "true"){
                self.key.identity = true
            }else{
                self.key.identity = false
            }
            self.orm.key = self.key
            break
        case LABEL_ITEM:
            self.item = DM_OrmItem()
            self.item.column = attributeDict[ATTRIBUTE_COLUMN]!
            self.item.columnType = attributeDict[ATTRIBUTE_COLUMN_TYPE]!
            self.item.property = attributeDict[ATTRIBUTE_PROPERTY]!
            self.item.propertyType = attributeDict[ATTRIBUTE_TYPE]!
            self.orm.items.append(self.item)
            break
            
        default:
            break
        }
    }
    
    // 监听解析成功并且结束时
    func parserDidEndDocument(_ parser: XMLParser) {
        
    }
    
}
